import { asyncRouterMap, constantRouterMap } from '@/router'
import user from './user'
import { getConstantsAttributeById } from '@/api/permission'
import { getCurUserBtnPerms } from '@/api/permission'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

// 设置自定义iframe大屏是否显示
function bigScreenVisibleSet(bigScreen, Routers) {
  if (bigScreen.length > 0) {
    for (const item of Routers) {
      if (item.name === 'sysExtendPage') {
        item.hidden = false
        item.children = bigScreen
      }
    }
  } else {
    for (const item of Routers) {
      if (item.name === 'sysExtendPage') {
        item.hidden = true
        item.children = bigScreen
      }
    }
  }
}

const permission = {
  namespaced: true,
  state: {
    // 静态路由
    routers: constantRouterMap,
    // 动态路由（异步加载）
    addRouters: [],
    // 按钮权限
    btnPerms: [],
    // 企业路由
    tenantRouters: [],
    // 未处理的动态路由，（拿到的后台路由数据）
    untreatedTRouter: sessionStorage.getItem('untreatedTRouter')
      ? sessionStorage.getItem('untreatedTRouter')
      : [],
    // sys-admin路由 用于返回sysAdmin
    sysRouter: [],
    // 自定义ifream大屏
    bigScreenR: [],
    // 自定义ifream大屏  sys-admin
    sysBigScreenR: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    ADD_T_ROUTERS: (state, tenantRouters) => {
      state.sysRouter = state.routers
      state.tenantRouters = tenantRouters
      state.routers = constantRouterMap.concat(tenantRouters)
    },
    SYS_ROUTER: state => {
      state.routers = state.sysRouter
      bigScreenVisibleSet(state.sysBigScreenR, state.routers)
      state.bigScreenR = state.sysBigScreenR
      state.tenantRouters = []
      state.untreatedTRouter = []
      sessionStorage.removeItem('untreatedTRouter')
    },
    SET_SYS_BIG_S: (state, routerInfo) => {
      bigScreenVisibleSet(routerInfo, state.routers)
      state.bigScreenR = routerInfo
    },
    SET_SYS_T_BIG: (state, routerInfo) => {
      state.sysBigScreenR = state.bigScreenR
      bigScreenVisibleSet(routerInfo, state.routers)
      state.bigScreenR = routerInfo
    },
    SET_CUR_USER_BTN_PERMS: (state, payload) => {
      state.btnPerms = payload
    },
    UNTREATED_T_ROUTER: (state, untreatedTRouter) => {
      // 未处理的project 的路由菜单
      state.untreatedTRouter = untreatedTRouter
      sessionStorage.setItem('untreatedTRouter', JSON.stringify(untreatedTRouter))
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise<void>(resolve => {
        const { roles } = data
        const extendRouter = data.getRouter
        const tempAR = [...asyncRouterMap]
        const asyncMainRouterMap = [...(extendRouter || []), ...tempAR]
        console.log(asyncMainRouterMap, '---route')

        const accessedRouters = filterAsyncRouter(asyncMainRouterMap, roles)
        commit('SET_ROUTERS', accessedRouters)

        if (roles[0] === 'CUSTOMER_USER') {
          resolve()
        } else {
          // 拿取扩展大屏
          const params = {
            type: 'sysBigScreen',
            key: 'sys_admin'
          }
          if (roles[0] === 'TENANT_ADMIN') {
            params.type = 'tenantBigScreen'
            params.key = user.state.tenantId
          }
          getConstantsAttributeById(params).then(res => {
            if (res.data[0]) {
              const rData = JSON.parse(res.data[0].value)
              const newRouter: any[] = []
              for (const item in rData) {
                const info = rData[item]
                if (info.state) {
                  const router = {
                    path: info.url,
                    name: item,
                    component: () => import('@/views/extendPage/sysPage.vue'),
                    meta: { title: info.name, icon: 'device' }
                  }
                  newRouter.push(router)
                }
              }
              commit('SET_SYS_BIG_S', newRouter)
            }
            resolve()
          })
        }
      })
    },
    addTRouters({ commit }, projectRouters) {
      const tempAR = [...asyncRouterMap]
      const asyncMainRouterMap = projectRouters.getRouter.concat(tempAR)

      const newRouters = filterAsyncRouter(asyncMainRouterMap, user.state.roles)
      console.log(newRouters, 'newRouters')
      commit('ADD_T_ROUTERS', newRouters)
    },
    untreatedTRouter({ commit }, untreatedTRouter) {
      commit('UNTREATED_T_ROUTER', untreatedTRouter)
    },
    sysRouter({ commit }) {
      commit('SYS_ROUTER')
    },
    setBigScreen({ commit }, routerInfo) {
      console.log(routerInfo, '---routerInfo')
      if (routerInfo.sysChange) {
        commit('SET_SYS_T_BIG', routerInfo.router)
      } else {
        commit('SET_SYS_BIG_S', routerInfo.router)
      }
    },
    async GetCurUserBtnPerms({ commit }) {
      const res = await getCurUserBtnPerms()
      console.log(res, 'GetCurUserBtnPermsGetCurUserBtnPerms')
      if (res.status === 200) commit('SET_CUR_USER_BTN_PERMS', res.data)
    },
    SetCurUserBtnPerms({ commit }, userBtnPerms) {
      commit('SET_CUR_USER_BTN_PERMS', userBtnPerms)
    }
  }
}

export default permission
